package filehandler;

import entity.PoemInfo;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class PullFromFile {
    /**
     * 从txt文件中读取诗词信息
     * @param filePath
     * @return 读取失败返回null
     */
    public static List<PoemInfo> pull(String filePath){
        FileInputStream file_fi = null;
        InputStreamReader file_sr = null;
        BufferedReader file = null;
        List<PoemInfo> poemInfoList = new ArrayList<PoemInfo>();
        try{
            file_fi = new FileInputStream(filePath);
            file_sr = new InputStreamReader(file_fi, "UTF-8");
            file = new BufferedReader(file_sr);
            boolean eof = false;

            while (!eof) {
                String line = file.readLine();
                if (line == null) {
                    eof = true;
                } else {
                    if (line.trim().equals("")){
                        System.err.println("有空行");
                    }
                    String[] parts = line.split("\t");
                    PoemInfo p = new PoemInfo();
                    p.title = parts[0];
                    p.author = parts[1];
                    p.content = parts[2];
                    p.tag = parts[3];
                    poemInfoList.add(p);
                }
            }
            return poemInfoList;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                file.close();
                file_sr.close();
                file_fi.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
